package com.example.springflowable.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springflowable.common.Results;
import com.example.springflowable.model.TaskModel;
import com.example.springflowable.service.TaskCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Classname TaskController
 * @Description TODO
 * @Date 2022/5/6 19:48
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Api(tags = "任务服务")
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskCommonService taskCommonService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ProcessEngine processEngine;




    @ApiOperation("获取用户待办")
    @GetMapping("getmytask")
    public JSONObject getMyTaskListController(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                              @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                              @RequestParam(value = "uid")String uid){
        List<TaskModel> taskModels=taskCommonService.getMyTaskList(uid,pageNum,pageSize);
        return Results.success(taskModels);
    }

    @ApiOperation("创建任务")
    @PostMapping("createTask")
    public JSONObject createTaskController(@ApiParam("流程id") @RequestParam("processKey")String processKey,
                                           @ApiParam("发给") @RequestParam("fromUid")String fromUid,
                                           @ApiParam("任务标题") @RequestParam("title")String title){
        String uuid= UUID.randomUUID().toString();
        Map<String,Object> map = new HashMap<>();
        map.put("uid",fromUid);
        ProcessInstance processInstance=taskCommonService.startProcess(processKey,uuid,title,fromUid,map);
        return Results.success("任务创建成功: "+processInstance.getId() );
    }



    @ApiOperation("提交任务")
    @PostMapping("submit")
    public JSONObject submitTaskController(@ApiParam("任务id")@RequestParam("taskid")String taskId){
      //  taskCommonService.complete();
        return null;
    }

    @ApiOperation("获取流程的历史节点")
    @GetMapping("gethistorybyprocessid")
    public JSONObject getHistoryController(@RequestParam("processId")String processInstanceId){
        List<HistoricTaskInstance> list=taskCommonService.getHistoricTaskListByProcessInstanceId(processInstanceId);
        return Results.success(list);
    }

    @ApiOperation("获取流程的任务列表")
    @GetMapping("gettasklistbypid")
    public JSONObject getTaskListController(@RequestParam("processId")String processInstanceId){
        List<Task> taskList=taskCommonService.getTaskListByProcessInstanceId(processInstanceId);
        for (Task task : taskList) {
            System.out.println(task.getId());
            System.out.println(task.getAssignee());
            System.out.println(task.getProcessDefinitionId());
            System.out.println(task.getCategory());
            System.out.println(task.getOwner());
        }
        return Results.success(taskList);
    }


    @GetMapping("/pic")
    public void showPic(HttpServletResponse resp, String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (pi == null) {
            return;
        }
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(processId)
                .list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        /**
         * 生成流程图
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, false);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = resp.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }


}
